package strategy

import (
	"fmt"
	"strings"
	"super/constant"
	"super/db"
	"super/global"

	"github.com/nguyenthenguyen/docx"
)

type SelectDocStrategy struct {
}

func (SelectDocStrategy) Init() {
	if db.Dao == nil {
		if err := db.InitDB(); err != nil {
			fmt.Println(err)
			fmt.Print("super>")
			return
		}
	}

	global.CurStatus = constant.SelectDoc
	fmt.Print("selectDoc>")
}

func (SelectDocStrategy) Handle(str string) {
	createSelectDoc(str)
	fmt.Print("selectDoc>")
}
func createSelectDoc(sql string) {
	if !strings.HasSuffix(sql, " limit 1") {
		sql += " limit 1"
	}
	rows, err := db.Dao.Query(sql)
	if err != nil {
		fmt.Println(err)
		return
	}

	replaceDocx, err := docx.ReadDocxFile("./insert.docx")
	if err != nil {
		fmt.Println(err)
		return
	}
	docx := replaceDocx.Editable()
	// docx.Replace("${db}", "lawsuit", 1)
	// docx.Replace("${table}", "tu_dm_kz", 1)

	columns, _ := rows.Columns()
	vals := make([]interface{}, len(columns))
	for i, _ := range columns {
		var v interface{}
		vals[i] = &v
	}
	rows.Next()
	rows.Scan(vals...)
	rows.Close()

	i := 0
	var empty interface{}
	for j, val := range vals {
		if *(val.(*interface{})) == empty {
			continue
		}

		docx.Replace(fmt.Sprintf("${h%d}", i), strings.ToLower(fmt.Sprintf("%v", columns[j])), 1)
		docx.Replace(fmt.Sprintf("${v%d}", i), fmt.Sprintf("%s", *(val.(*interface{}))), 1)
		i++
	}

	err = docx.WriteToFile("./insertFinish.docx")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("create successful!")
	}
	replaceDocx.Close()
}
